package com.weng.platform.apiManager.mock.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.weng.framework.core.exception.GlobalServiceException;
import com.weng.framework.core.model.ResponseData;
import com.weng.framework.dao.mybatis.model.page.PageModel;
import com.weng.framework.dao.mybatis.service.BaseServiceImpl;
import com.weng.platform.apiManager.mock.entity.ApiMock;
import com.weng.platform.apiManager.mock.mapper.ApiMockMapper;
import com.weng.platform.apiManager.mock.service.IApiMockService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.Arrays;
import java.util.List;


/**
 * api的mock数据 服务实现类
 *
 * @author wenghui
 * @date 2020-09-22 13:44:15
 *
 */ 
@Slf4j
@Service
public class ApiMockServiceImpl extends BaseServiceImpl<ApiMockMapper, ApiMock> implements IApiMockService {
	@Autowired
	private ApiMockMapper apiMockMapper;
	
    /*
     * 获取mock数据
     * @param [url, param]
     * @return
     */
    @Override
	public JSONObject getMockData(String url , String param){
        QueryWrapper<ApiMock> qw = new QueryWrapper<>();
        qw.eq("url", url.trim());
        if(StringUtils.isNotEmpty(param)){
            qw.eq("param", param.trim());
        }
        List<ApiMock> list = apiMockMapper.selectList(qw);
        if(list != null && list.size() > 0){
            JSONObject jsonData =  JSONObject.parseObject(list.get(0).getMock());
            return jsonData;
        }
        return null;
    }

	/**
	 * 分页查询api的mock数据
	 * @return
	 */
	@Override
	public IPage<ApiMock> list(Integer pageNo,Integer pageSize) {
		QueryWrapper<ApiMock> qw = new QueryWrapper<ApiMock>();
		IPage<ApiMock> page = new PageModel<ApiMock>(pageNo,pageSize);
		return apiMockMapper.selectPage(page,qw);
	}


	/**
	 * 获取单个api的mock数据
	 * @param id
	 * @return
	 */
	@Override
	public ApiMock getById(Serializable id) {
		return super.getById(id);
	}

	/**
	 * 新增单个api的mock数据
	 * @param apiMock
	 * @return
	 */
	@Override
	public ApiMock add(ApiMock apiMock) throws GlobalServiceException {
		
		apiMockMapper.insert(apiMock);
		return apiMock;
	}

	/**
	 * 更新单个api的mock数据
	 * @param apiMock
	 * @return
	 * @throws GlobalServiceException
	 */
	@Override
	public int update(ApiMock apiMock) throws GlobalServiceException {
		
		return apiMockMapper.updateById(apiMock);

	}


	@Override
	public ResponseData removeByIds(String ids) {
		String[] apiMockIds = ids.split(",");
		boolean flag = this.removeByIds(Arrays.asList(apiMockIds));
		if (flag) {
			return ResponseData.success();
		} else {
		    return ResponseData.failed();
		}
	}

}
